package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.model.node.ext.canJoin
import com.gitee.wsl.doc.prosemirror.model.node.ext.joinPoint
import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.NodeSelection
import com.gitee.wsl.doc.prosemirror.transform.ext.join

object JoinDown: Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val sel = state.selection
        val point:Int?
        if (sel is NodeSelection) {
            if (sel.node.isTextblock || !state.doc.canJoin( sel.to)) return false
            point = sel.to
        } else {
            point = state.doc.joinPoint( sel.to, 1)
            if (point == null) return false
        }
        if (dispatch!=null)
            dispatch(state.tr.join(point).scrollIntoView())
        return true
    }
}

/// Join the selected block, or the closest ancestor of the selection
/// that can be joined, with the sibling after it.
val Command.Companion.joinDown get() = JoinDown